import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import { useAuthStore } from '@/store/auth'
import { useNotificationStore } from '@/store/notifications'
import { useChatStore } from '@/store/chat'

class WebSocketService {
  constructor() {
    this.stompClient = null
    this.isConnected = false
    this.reconnectTimer = null
  }

  // 初始化连接
  initConnection() {
    const authStore = useAuthStore()
    if (!authStore.token) {
      console.error('WebSocket 连接失败：未登录（无 Token）')
      return
    }

    // 走相对路径，让 Vite 代理处理跨域和 Token
const socket = new SockJS(`/ws?token=${authStore.token}`)
    this.stompClient = Stomp.over(socket)

    this.stompClient.heartbeat.outgoing = 0
    this.stompClient.heartbeat.incoming = 0

    this.stompClient.connect({},
      (frame) => {
        this.isConnected = true
        console.log('WebSocket 连接成功', frame)
        this.clearReconnectTimer()
        this.subscribeUserChannels(authStore.user.id)
      },
      (error) => {
        this.isConnected = false
        console.error('WebSocket 连接失败', error)
        this.startReconnectTimer()
      }
    )
  }

  // 订阅用户频道
  subscribeUserChannels(userId) {
    const notificationStore = useNotificationStore()
    const chatStore = useChatStore()

    // 通知频道
    this.stompClient.subscribe(`/user/${userId}/notifications`, (message) => {
      const newNotification = JSON.parse(message.body)
      console.log('收到新通知', newNotification)
      notificationStore.notifications.unshift(newNotification)
    })

    // 聊天频道
    this.stompClient.subscribe(`/chat/${userId}`, (message) => {
      const newMessage = JSON.parse(message.body)
      console.log('收到新聊天消息', newMessage)
      chatStore.addChatMessage(newMessage)
    })
  }

  sendMessage(destination, data) {
    if (!this.isConnected || !this.stompClient) {
      console.error('WebSocket 未连接，无法发送消息')
      return false
    }
    this.stompClient.send(destination, {}, JSON.stringify(data))
    return true
  }

  disconnect() {
    if (this.stompClient) {
      this.stompClient.disconnect()
      this.isConnected = false
      this.clearReconnectTimer()
      console.log('WebSocket 已断开连接')
    }
  }

  startReconnectTimer() {
    this.clearReconnectTimer()
    this.reconnectTimer = setTimeout(() => {
      console.log('WebSocket 尝试重连...')
      this.initConnection()
    }, 3000)
  }

  clearReconnectTimer() {
    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer)
      this.reconnectTimer = null
    }
  }
}

export default new WebSocketService()